package com.lorizz.picpub.util;

import java.util.UUID;

public class IdGenerator {

	private static char[] TRANSLATE;

	static {
		TRANSLATE = new char[64];
		int i = 0;
		for (char c = '0'; c <= '9'; c++) {
			TRANSLATE[i] = c;
			i++;
		}
		for (char c = 'a'; c <= 'z'; c++) {
			TRANSLATE[i] = c;
			i++;
		}
		for (char c = 'A'; c <= 'Z'; c++) {
			TRANSLATE[i] = c;
			i++;
		}
		TRANSLATE[i] = '-';
		TRANSLATE[++i] = '_';
	}

	public static String generate() {
		return generateFromUuid(UUID.randomUUID());
	}
	
	public static String generateFromUuid(String uuid) {
		return generateFromUuid(UUID.fromString(uuid));
	}

	public static String generateFromUuid(UUID uuid) {
		long msb = uuid.getMostSignificantBits();
		long lsb = uuid.getLeastSignificantBits();
		StringBuilder s = new StringBuilder();
		for (int i = 1; i <= 10; i++) {
			int pos = (int) (msb >>> (64 - (6 * i)) & 63);
			s.append(TRANSLATE[pos]);
		}
		s.append(TRANSLATE[(int) (msb & 15 << 2 | (lsb >>> 62) & 63)]);
		for (int i = 1; i <= 10; i++) {
			int pos = (int) (lsb >>> (64 - (2 + 6 * i)) & 63);
			s.append(TRANSLATE[pos]);
		}
		s.append(TRANSLATE[(int) lsb & 3]);
		return s.toString();
	}
}
